import router from './router'
import store from './store'
import { getToken } from '@/utils/auth' // 验权

function hasPermission(roles, permissionRoles) {
  if (roles.indexOf('admin') >= 0) return true // admin permission passed directly
  if (!permissionRoles) return true
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}

// 初始化路由
function initRoutes() {
  const roles = { roles: ['admin'] }
  store.dispatch('GenerateRoutes', roles).then(() => { // 根据roles权限生成可访问的路由表
    router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
  })
}
initRoutes()

const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (hasPermission(['admin'], to.meta.roles)) {
      next()
    } else {
      next({ path: '/401', replace: true, query: { noGoBack: true }})
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})
